package com.payment.service.alast.impl;

import com.alibaba.fastjson.JSON;
import com.payment.config.dto.ResultDataDto;
import com.payment.config.dto.StringOutputConstant;
import com.payment.entity.alast.common.PartnerPayPalReceiveAccount;
import com.payment.entity.alast.common.PartnerShowWeChatPay;
import com.payment.entity.alast.common.ServicePlanOrderAutoRenewalRecord;
import com.payment.entity.alast.common.ServicePlanOrderRecord;
import com.payment.entity.alast.filterpayment.request.RequestFilterPayment;
import com.payment.entity.alast.filterpayment.response.ResponseFilterPayment;
import com.payment.entity.alast.paypalpay.request.RequestPayPalWebPay;
import com.payment.entity.alast.paypalpay.response.ResponsePayPalWebPay;
import com.payment.entity.alast.resultconfirm.request.RequestResultConfirm;
import com.payment.entity.alast.resultconfirm.response.ResponseResultConfirm;
import com.payment.entity.alast.resultquery.request.RequestResultQuery;
import com.payment.entity.alast.resultquery.response.ResponseResultQuery;
import com.payment.entity.alast.showwechatpay.request.RequestShowWeChatPay;
import com.payment.entity.alast.showwechatpay.response.ResponseShowWeChatPay;
import com.payment.entity.alast.stripe.autorenewal.setupintent.request.RequestStripeAutoPay;
import com.payment.entity.alast.stripe.autorenewal.setupintent.response.SetupIntentResponse;
import com.payment.entity.alast.stripe.autorenewal.subcription.cancel.request.RequestStripeSubCancel;
import com.payment.entity.alast.stripe.autorenewal.subcription.cancel.response.SubscriptionCancelResponse;
import com.payment.entity.alast.stripe.autorenewal.subcription.directly.request.RequestStripeSubDirectly;
import com.payment.entity.alast.stripe.autorenewal.subcription.directly.request.SubscriptionDirectlyPlan;
import com.payment.entity.alast.stripe.autorenewal.subcription.directly.request.SubscriptionDirectlyProduct;
import com.payment.entity.alast.stripe.autorenewal.subcription.directly.request.SubscriptionDirectlyRequest;
import com.payment.entity.alast.stripe.autorenewal.subcription.directly.response.SubscriptionDirectlyResponse;
import com.payment.entity.alast.stripe.autosubcon.StripeSubJsonBody;
import com.payment.entity.alast.stripe.ontimecon.ChargesData;
import com.payment.entity.alast.stripe.ontimecon.StripeJsonRootBean;
import com.payment.entity.alast.stripe.onetime.request.RequestStripePay;
import com.payment.entity.alast.stripe.onetime.response.CreateStripePaymentResponse;
import com.payment.entity.alast.wxwebpay.request.RequestWeiXinWebPay;
import com.payment.entity.alast.wxwebpay.response.ResponseWeiXinWebPay;
import com.payment.mapper.alast.PaymentAndResultMapper;
import com.payment.service.alast.PaymentAndResultService;
import com.payment.utils.Constant;
import com.payment.utils.Md5Encrypt;
import com.payment.utils.payment.PayPalConstants;
import com.payment.utils.payment.WeiXinPayUtil;
import com.payment.utils.payment.WxPayConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 1，请求支付的接口：微信H5支付接口；paypal的H5支付接口
 * 2，请求支付结果的接口：微信的支付结果；paypal的支付结果；异常延时订单的支付结果确认。
 * <p>
 * 如果要将xml或者json的格式去掉的话：String x = strResult.replaceAll("\n", "");
 *
 * @author lm
 * @date 2020/7/31 10:00
 */
@Service
public class PaymentAndResultServiceImpl implements PaymentAndResultService {
    private static Logger logger = Logger.getLogger(PaymentAndResultServiceImpl.class);
    @Resource
    PaymentAndResultMapper paymentAndResultMapper;
    @Autowired
    AssistComLogicServiceImpl comLogicService;
    @Autowired
    AfterPayDeal afterPayDeal;
    @Autowired
    ToBeijingCheckoutService toBeijingCheckoutService;
    /**
     * stripe收款的邮箱
     */
    @Value("${stripe.receiptEmail}")
    private String receiptEmail;

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 计算settlePrice值
     *
     * @param fee
     * @return
     */
    private String setSettlePrice(float fee, String currency) {
        String settlePrice;
        if (fee <= StringOutputConstant.TEST_AMOUNT) {
            settlePrice = "0.00";
        } else {
            if (currency.equalsIgnoreCase(StringOutputConstant.EUR)) {
                settlePrice = String.format("%1.2f", fee * 1.18);
            } else {
                settlePrice = String.format("%1.2f", fee);
            }
        }
        return settlePrice;
    }

    /**
     * @param request
     * @return
     */
    @Override
    public ResultDataDto filterPayment(RequestFilterPayment request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("过滤支付请求：" + JSON.toJSONString(request));

        if (StringUtils.isBlank(request.getPartnerCode()) || StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        //第一件事情是先去将支付结果入库：
        Integer payIdCount = comLogicService.findCountByNo(request.getPayId());
        if (payIdCount <= 0) {
            return ResultDataDto.addOperationFailure("payId有误");
        }

        //单价
        float fee = Float.parseFloat(request.getPayAmount()) / payIdCount;
        //总价
        float fee1 = Float.parseFloat(request.getPayAmount());
        //支付的总金额相当于付款时的金额
        String payAmount = String.format("%1.2f", fee1);
        //支付的总金额/订单条数=每笔订单支付的单价
        String payUnit = String.format("%1.2f", fee);

        String settlePrice;
        if (fee <= StringOutputConstant.TEST_AMOUNT) {
            settlePrice = "0.00";
        } else {
            settlePrice = String.format("%1.2f", fee / 7);
        }
        logger.info("out_trade_no(订单号)为：" + request.getPayId() + ";total_fee(金额)为:" + request.getPayAmount() + ";payAmount为:" + payAmount + ";settlePrice为：" + settlePrice);

        //2，不管是不是成功的记录都需要去入库，根据支付id和金额入库：service_plan_order_record_t
        Integer upReCount = comLogicService.updateOrderRecordT(request.getPayId(), payUnit, payAmount, "CNY", settlePrice, "TEST0001", StringOutputConstant.CODE_PAY_WEIXIN, "SUCCESS", "1");

        if (upReCount > 0) {
            logger.info(request.getPayId() + ":service_plan_order_record_t更新记录成功");
            //丢去redis做后面该做当然事情
            afterPayDeal.addPayIdToRedis(request.getPayId());

            List<ServicePlanOrderRecord> reList = paymentAndResultMapper.querySuccessfulOrderRecords(request.getPartnerCode(), request.getPayId());

            for (ServicePlanOrderRecord record : reList) {
                //成功
                ResponseFilterPayment response = new ResponseFilterPayment();
                response.setPartnerCode(record.getPartnerCode());
                response.setPayRst("success");
                response.setPayId(record.getPayId());
                if ("CNY".equalsIgnoreCase(record.getPayCurrency())) {
                    response.setPayAmount("￥" + record.getPayAmount());
                } else if ("EUR".equalsIgnoreCase(record.getPayCurrency())) {
                    response.setPayAmount("€" + record.getPayAmount());
                } else {
                    response.setPayAmount("$" + record.getPayAmount());
                }
                response.setServicePlanShowName(record.getServicePlanShowName());
                response.setOrderPeriod(comLogicService.setOrderPeriod(record.getPackageType(), record.getOrderPeriod()));
                response.setPackageType(record.getPackageType());
                if (StringUtils.isNotBlank(record.getPayResultDate())) {
                    response.setPayResultDate(record.getPayResultDate());
                } else {
                    response.setPayResultDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                }
                logger.info("过滤成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }
        }

        logger.info("过滤失败响应");
        return ResultDataDto.addOperationFailure("过滤失败");
    }

    /**
     * 请求：获取微信网页（H5）支付权限
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto wxWebPay(RequestWeiXinWebPay request, HttpServletRequest re) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("获取微信网页（H5）支付权限请求：" + JSON.toJSONString(request));

        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) ||
                StringUtils.isBlank(request.getPartnerCode()) || StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount()) || StringUtils.isBlank(request.getSign()) ||
                null == request.getAppid() || null == request.getMch_id() || null == request.getBody() || null == request.getScene_info() || null == request.getKey()) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        String sign = Md5Encrypt.jsonSign(request);

        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }

        //这些参数是去微信预下单的必要参数
        String appId = "";
        String mchId = "";
        String body = "";
        String key = "";
        String sceneInfo = "";

        String prePayInfoXml = "";
        // 获取用户的ip地址:
        String ipAddrStr = WeiXinPayUtil.getIp2(re);
        //判断请求的数字是整型还是带小数点
        boolean flag = WeiXinPayUtil.isInteger(request.getPayAmount());

        //现在开始判断是否走领科自己的微信收款渠道:
        if (StringUtils.isNotBlank(request.getAppid()) && StringUtils.isNotBlank(request.getMch_id()) && StringUtils.isNotBlank(request.getBody()) && StringUtils.isNotBlank(request.getScene_info()) && StringUtils.isNotBlank(request.getKey())) {
            //如果传过来的这些参数都是有值的就走传过来的渠道
            appId = request.getAppid();
            mchId = request.getMch_id();
            body = request.getBody();
            key = request.getKey();
            sceneInfo = request.getScene_info();
        } else {
            //否则就是走领科自己本身的渠道收款
            appId = WxPayConstants.APPID;
            mchId = WxPayConstants.MCH_ID;
            body = WxPayConstants.body;
            key = WxPayConstants.KEY;
            sceneInfo = WxPayConstants.scene_Info;
        }

        //现在去微信预下单：
        try {
            //整型金额
            if (flag) {
                int amount = Integer.parseInt(request.getPayAmount());
                int totalFee = amount * 100;
                prePayInfoXml = WeiXinPayUtil.UnifiedOrderH5(request.getPayId(), totalFee, appId, mchId, body, sceneInfo, key, ipAddrStr);
            } else {
                // DecimalFormat("#")表示float类型格式化时不要小数点了
                DecimalFormat decimalFormat = new DecimalFormat("#");
                float amount = Float.parseFloat(request.getPayAmount());
                int totalFee = Integer.parseInt(decimalFormat.format(amount * 100));
                prePayInfoXml = WeiXinPayUtil.UnifiedOrderH5(request.getPayId(), totalFee, appId, mchId, body, sceneInfo, key, ipAddrStr);
            }
        } catch (Exception e) {
            logger.info("去微信预下单UnifiedOrderH5方法发生异常：" + e);
            return ResultDataDto.addOperationException(StringOutputConstant.CODE_EXCEPTION_WECHAT);
        }

        //微信预下单的结果有误时：
        if (StringUtils.isBlank(prePayInfoXml)) {
            logger.info("微信预下单响应prePayInfoXml返回为空");
            return ResultDataDto.addOperationException(StringOutputConstant.CODE_PRE_ORDER_ERROR);
        }

        //开始解析微信预下单的结果，将微信预下单的结果转成 Map<String, Object>形式：
        Map<String, Object> map = WeiXinPayUtil.getPayH5Map(prePayInfoXml);

        if (null == map || map.size() == 0) {
            logger.info("微信预下单响应转成map有误");
            return ResultDataDto.addOperationException(StringOutputConstant.CODE_PRE_ORDER_ERROR);
        }

        //现在开始解析map把参数取出来，先判断返回成不成功
        String resultCode = map.get("result_code") + "";
        String returnCode = map.get("return_code") + "";

        if (StringUtils.isNotBlank(resultCode) && StringUtils.isNotBlank(returnCode) && StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(resultCode) && StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(returnCode)) {

            //然后再判断成功之后参数有没有效
            String prepayId = map.get("prepay_id") + "";
            String mWebUrl = map.get("mweb_url") + "";

            if (StringUtils.isNotBlank(prepayId) && StringUtils.isNotBlank(mWebUrl)) {
                //可以正常返回
                ResponseWeiXinWebPay response = new ResponseWeiXinWebPay();
                response.setPrepay_id(prepayId);
                response.setMweb_url(mWebUrl);
                response.setPayId(request.getPayId());
                response.setPartnerCode(request.getPartnerCode());
                logger.info("【微信预下单】成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }
        }
        logger.info("微信预下单失败");
        return ResultDataDto.addOperationException(StringOutputConstant.CODE_ORDER_FAILED);
    }

    /**
     * 请求：获取payPal网页（H5）支付权限
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto payPalPay(RequestPayPalWebPay request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }

        logger.info("获取payPal网页（H5）支付权限请求：" + JSON.toJSONString(request));

        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) ||
                StringUtils.isBlank(request.getPartnerCode()) || StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount()) || StringUtils.isBlank(request.getSign()) ||
                StringUtils.isBlank(request.getMode()) || null == request.getClientId() || null == request.getClientSecret()) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        String sign = Md5Encrypt.jsonSign(request);

        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }

        //mode只允许有sandbox和production两个值
        if (request.getMode().equalsIgnoreCase(StringOutputConstant.CODE_SANDBOX) || request.getMode().equalsIgnoreCase(StringOutputConstant.CODE_PRODUCTION)) {

            String clientId = "";
            String clientSecret = "";
            //确定给前端返回哪个ClientId和ClientSecret

            if (StringUtils.isNotBlank(request.getClientId()) && StringUtils.isNotBlank(request.getClientSecret())) {
                clientId = request.getClientId();
                clientSecret = request.getClientSecret();
            } else {
                boolean b1 = (StringUtils.isBlank(request.getClientId()) || StringUtils.isBlank(request.getClientSecret())) && request.getMode().equalsIgnoreCase(StringOutputConstant.CODE_SANDBOX);
                boolean b2 = (StringUtils.isBlank(request.getClientId()) || StringUtils.isBlank(request.getClientSecret())) && request.getMode().equalsIgnoreCase(StringOutputConstant.CODE_PRODUCTION);
                PartnerPayPalReceiveAccount account;

                //生产环境mode=production
                if (b2) {
                    if (StringOutputConstant.CODE_P000270.equals(request.getPartnerCode())) {
                        if (active.equals(StringOutputConstant.CODE_TEST)) {
                            /*gary@linksfield.net*/
                            clientId = "AdBWXC3METPkPQ5apSZK8-QBAd2XohYbilmAMo3ZhNW-1g092o-4q7NSKs5CNAxge-NYMDNlti__ViuW";
                            clientSecret = "ELkwkorOAVfikSp7v6byKm6RVQme3Mu1ODOjpcqONJkg_IsXQc2xCoXcGyCSAjFPxFdSyx13PAYyBjry";
                        } else {
                            /*b2b2c@linksfield.net*/
                            clientId = "ATEL7Z1T5hcKXZ9ii-uFf26e4F16jzZKAzLnlDNzh5TAvjO5VjjlthatA_WNfYpKRI22r6M4LNdn20a5";
                            clientSecret = "EJAPvUc2XiKBMtv1xLwwAO3qmhwiaf_9Bvmz0MlTQOavsLnMMzeadimynKq4F-49H43cOfN9zVA8AO_w";
                        }
                    } else {
                        account = paymentAndResultMapper.queryAccountByCode(request.getPartnerCode(), "1", "1");
                        if (null != account) {
                            //数据库里面有这个企业相关的账户配置
                            clientId = account.getClientId();
                            clientSecret = account.getClientSecret();
                        } else {
                            //数据库里面没有这个企业相关的账户配置，这个时候需要确定一下现在是什么环境
                            if (active.equals(StringOutputConstant.CODE_TEST)) {
                                //如果是测试环境需要用固定的：gary@linksfield.net账号
                                account = paymentAndResultMapper.queryAccountByCode("P000270", "1", "2");
                                if (null != account) {
                                    clientId = account.getClientId();
                                    clientSecret = account.getClientSecret();
                                } else {
                                    //程序有问题了
                                    clientId = "AdBWXC3METPkPQ5apSZK8-QBAd2XohYbilmAMo3ZhNW-1g092o-4q7NSKs5CNAxge-NYMDNlti__ViuW";
                                    clientSecret = "ELkwkorOAVfikSp7v6byKm6RVQme3Mu1ODOjpcqONJkg_IsXQc2xCoXcGyCSAjFPxFdSyx13PAYyBjry";
                                }
                            } else {
                                //非测试环境就应该用正常的：b2b2c@linksfield.net账号
                                account = paymentAndResultMapper.queryAccountByCode("P000270", "1", "1");
                                if (null != account) {
                                    clientId = account.getClientId();
                                    clientSecret = account.getClientSecret();
                                } else {
                                    //程序有问题了
                                    clientId = "ATEL7Z1T5hcKXZ9ii-uFf26e4F16jzZKAzLnlDNzh5TAvjO5VjjlthatA_WNfYpKRI22r6M4LNdn20a5";
                                    clientSecret = "EJAPvUc2XiKBMtv1xLwwAO3qmhwiaf_9Bvmz0MlTQOavsLnMMzeadimynKq4F-49H43cOfN9zVA8AO_w";
                                }
                            }
                        }

                    }
                }
                //测试环境mode=sandbox
                if (b1) {
                    account = paymentAndResultMapper.queryAccountByCode(request.getPartnerCode(), "0", "1");
                    if (null != account) {
                        //数据库里面有这个企业相关的账户配置
                        clientId = account.getClientId();
                        clientSecret = account.getClientSecret();
                    } else {
                        //数据库里面没有这个企业相关的账户配置，这个时候需要确定一下现在是什么环境
                        account = paymentAndResultMapper.queryAccountByCode("P000270", "0", "1");
                        if (null != account) {
                            clientId = account.getClientId();
                            clientSecret = account.getClientSecret();
                        } else {
                            //程序有问题了
                            clientId = "AVfmRTgDbD_hDDR5s-v7wzkJXkTPaifLEhwpf_FPatkf8XBKOpKZLrtQagwnZNk4kELgeQgWI6d7YRYH";
                            clientSecret = "EPtR67e1FK85rKyS9vnWATZzGcK97Wysxviska_Y8bxvtEYNkwf7bfNtAZHUfJBbEQlxFoAR01VlLcJ1";
                        }
                    }
                }
            }
            //返回：
            ResponsePayPalWebPay response = new ResponsePayPalWebPay();
            response.setClientId(clientId);
            response.setClientSecret(clientSecret);
            response.setMode(request.getMode());
            response.setPayId(request.getPayId());
            response.setPartnerCode(request.getPartnerCode());

            logger.info("【payPay预下单】成功响应：" + JSON.toJSONString(response));
            return ResultDataDto.addOperationSuccess().setData(response);

        } else {
            logger.info("mode的值不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_MODE_ILLEGAL_ERROR);
        }
    }

    /**
     * 请求：微信或者payPal支付结果查询
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto resultQuery(RequestResultQuery request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }

        logger.info("微信或者payPal支付结果查询请求：" + JSON.toJSONString(request));

        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) ||
                StringUtils.isBlank(request.getPartnerCode()) || StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        String sign = Md5Encrypt.jsonSign(request);

        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }

        try {

            //来查询的时候
            logger.info("查询支付结果可能延迟~先等待10秒再执行！");
            Thread.sleep(10000);

            //查询数据库看看当前这个订单的支付记录入库了没有，当然这个时候很有可能支付结果还没有到位。

            List<ServicePlanOrderRecord> recordList = paymentAndResultMapper.querySuccessfulOrderRecords(request.getPartnerCode(), request.getPayId());

            if (null != recordList && !recordList.isEmpty()) {

                ResponseResultQuery response = null;

                for (ServicePlanOrderRecord record : recordList) {

                    response = new ResponseResultQuery();
                    response.setPartnerCode(record.getPartnerCode());
                    response.setPayRst("success");
                    response.setPayId(record.getPayId());

                    if ("EUR".equalsIgnoreCase(record.getPayCurrency())) {
                        response.setPayAmount("€ " + record.getPayAmount());
                    } else if ("USD".equalsIgnoreCase(record.getPayCurrency())) {
                        response.setPayAmount("$ " + record.getPayAmount());
                    } else {
                        response.setPayAmount("￥ " + record.getPayAmount());
                    }
                    response.setServicePlanShowName(record.getServicePlanShowName());
                    response.setOrderPeriod(comLogicService.setOrderPeriod(record.getPackageType(), record.getOrderPeriod()));
                    response.setPackageType(record.getPackageType());
                    response.setPayResultDate(record.getPayResultDate());
                }

                logger.info("【微信或者payPal支付结果查询】成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }
        } catch (Exception e) {
            logger.info("查询支付结果延迟执行过程遇到异常：" + e);
        }

        //走到这边：要么就是订单的成功结果还没有入库，要么就是未支付,这边给前端一个结果延迟的提示
        logger.info("支付结果可能存在延迟，也有可能是未支付！");
        return ResultDataDto.addOperationException(StringOutputConstant.CODE_DELAYS_RESULTS);
    }

    /**
     * 请求：微信或者payPal支付结果确认
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto resultConfirm(RequestResultConfirm request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }

        logger.info("微信或者payPal支付结果查询请求：" + JSON.toJSONString(request));

        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getPartnerCode()) ||
                StringUtils.isBlank(request.getPayId()) || null == request.getAppid() || null == request.getMch_id() || null == request.getKey() || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        String sign = Md5Encrypt.jsonSign(request);

        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }

        try {

            //跳到这边说明已经延迟了，那我们先等10秒再查
            logger.info("已经延迟~先等10秒再查~");
            Thread.sleep(10000);

            //开始查数据库的时候还没有支付时间，先用这个代替
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            //1,先去数据库查一下有没有这条记录的支付结果数据
            List<ServicePlanOrderRecord> recordList = paymentAndResultMapper.querySuccessfulOrderRecords(request.getPartnerCode(), request.getPayId());

            //2，微信或者payPal支付结果查询成功响应：
            if (null != recordList && !recordList.isEmpty()) {
                ResponseResultConfirm response = comLogicService.responseRecord(recordList, "success", date);
                //2，如果有成功的记录就直接返回的呀
                logger.info("【微信或者payPal支付结果查询】成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }

            //4，走到这边说明数据库里面也还是没有查到成功的记录，这个时候我们就要确认这个订单是不是在数据库里面
            List<ServicePlanOrderRecord> resList = paymentAndResultMapper.queryRecordExists(request.getPartnerCode(), request.getPayId());
            if (null == resList || resList.isEmpty()) {
                logger.info("payId根本不在数据库里，说明没有这个订单");
                return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PAYID_ILLEGAL_ERROR);
            }

            //6，如果走这里说明订单是到库了的，只是结果可能还没有到，那我们现在检索一下订单是哪种支付方式，所有的订单我们都去微信查询一遍
            //这些参数是去微信查询订单的必要参数
            String appId;
            String mchId;
            String key;
            String transactionId = "";
            String payId = request.getPayId();

            //看看参数从哪里获得
            if (StringUtils.isNotBlank(request.getAppid()) && StringUtils.isNotBlank(request.getMch_id()) && StringUtils.isNotBlank(request.getKey())) {
                //如果传过来的这些参数都是有值的就走传过来的渠道
                appId = request.getAppid();
                mchId = request.getMch_id();
                key = request.getKey();
            } else {
                //否则就是走领科自己本身的渠道收款
                appId = WxPayConstants.APPID;
                mchId = WxPayConstants.MCH_ID;
                key = WxPayConstants.KEY;
            }

            //7，现在去微信查询订单支付结果：
            String prePayInfoXml = WeiXinPayUtil.weixinQuery(transactionId, payId, appId, mchId, key);

            if (StringUtils.isBlank(prePayInfoXml)) {
                logger.info("微信查询遇到了问题");
                return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PAYTYPE_ILLEGAL_ERROR);
            }

            //8,开始解析微信查询的结果，将微信查询的结果转成 Map<String, Object>形式：
            Map<String, Object> map = WeiXinPayUtil.getWeiXinQueryMap(prePayInfoXml);

            if (null == map || map.size() == 0) {
                logger.info("微信查询响应转成map有误");
                return ResultDataDto.addOperationException(StringOutputConstant.CODE_QUERY_ORDER_ERROR);
            }

            //9，现在开始解析map把参数取出来，先判断返回成不成功
            String resultCode = map.get("result_code") + "";
            String returnCode = map.get("return_code") + "";
            String tradeState = map.get("trade_state") + "";
            String tradeStateDesc = map.get("trade_state_desc") + "";

            //10，现在解析微信支付结果
            if (StringUtils.isNotBlank(resultCode) && StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(resultCode) &&
                    StringUtils.isNotBlank(returnCode) && StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(returnCode) && StringUtils.isNotBlank(tradeState)) {

                //11,在微信查询到了这个订单，现在开始判断是不是支付成功：
                if (StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(tradeState)) {
                    //12,微信支付结果查询成功
                    ResponseResultConfirm response = comLogicService.responseRecord(resList, "success", date);
                    logger.info("【微信支付结果查询】成功响应：" + JSON.toJSONString(response));
                    return ResultDataDto.addOperationSuccess().setData(response);
                }

                //14，微信结果查询到了，不过不是成功的支付结果,所以我们对这所有的状态统称为“fail”
                logger.info("微信查询订单：" + payId + ":结果是：" + tradeStateDesc + ";Payment Failure:" + tradeState);
                ResponseResultConfirm response = comLogicService.responseRecord(resList, "failed", date);
                logger.info("【微信支付结果查询】成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }

            //15,说明可能在微信并没有查询到这个订单，可能是payPal支付的,继续等待并且再查询一遍
            logger.info("微信没有查询到~再等5秒再查~");
            Thread.sleep(10000);

            //16,短暂等待之后先去数据库查一下有没有这条记录的支付结果数据
            List<ServicePlanOrderRecord> reList = paymentAndResultMapper.querySuccessfulOrderRecords(request.getPartnerCode(), request.getPayId());

            //17，payPal支付结果查询响应：
            if (null != reList && !reList.isEmpty()) {
                ResponseResultConfirm response = comLogicService.responseRecord(reList, "success", date);
                //18，如果有成功的记录就直接返回的呀
                logger.info("【payPal支付结果查询】成功响应：" + JSON.toJSONString(response));
                return ResultDataDto.addOperationSuccess().setData(response);
            }

            //19，payPal订单还是没有成功的结果到数据库，不管是不是真的延迟了这会儿一定要给用户结果，这边当成失败返回
            ResponseResultConfirm response = comLogicService.responseRecord(resList, "failed", date);
            logger.info("【支付结果确认接口】成功响应：" + JSON.toJSONString(response));
            return ResultDataDto.addOperationSuccess().setData(response);

        } catch (Exception e) {
            logger.info("支付结果确认接口延迟执行过程遇到异常：" + e);
        }

        //19，还是没有查到直接按照失败处理了
        logger.info("到这边的是接口层面的失败");
        return ResultDataDto.addOperationFailure();
    }

    /**
     * 微信支付结果回调
     *
     * @param resXml
     * @return
     */
    @Override
    public String wxNotify(String resXml) {
        logger.info("微信回调的内容是：" + resXml.replaceAll("\n", ""));
        //说明resXml是有值的：
        String return_code = WeiXinPayUtil.getXmlPara(resXml, "return_code") + "";
        String result_code = WeiXinPayUtil.getXmlPara(resXml, "result_code") + "";
        String return_msg = WeiXinPayUtil.getXmlPara(resXml, "return_msg") + "";
        String out_trade_no = WeiXinPayUtil.getXmlPara(resXml, "out_trade_no") + "";
        String total_fee = WeiXinPayUtil.getXmlPara(resXml, "total_fee") + "";
        String fee_type = WeiXinPayUtil.getXmlPara(resXml, "fee_type") + "";
        String transaction_id = WeiXinPayUtil.getXmlPara(resXml, "transaction_id") + "";
        logger.info("微信返回码：" + return_code + "微信结果码:" + result_code);

        //判断通信标识，以便做不同响应
        if (StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(return_code)) {

            //4,去数据库核对或者更新记录记录表里面有没有这条记录
            if (StringUtils.isNotBlank(out_trade_no) && StringUtils.isNotBlank(total_fee) && StringUtils.isNotBlank(fee_type) && StringUtils.isNotBlank(transaction_id) && StringUtils.isNotBlank(result_code)) {

                //1，查询out_trade_no在数据库有几条记录。查询不到这条记录可以直接返回
                Integer payIdCount = comLogicService.findCountByNo(out_trade_no);
                if (payIdCount <= 0) {
                    logger.info("invoice:" + out_trade_no + "：不是领科系统的支付单号");
                    String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[out_trade_no有误]]></return_msg>" + "</xml> ";
                    return result;
                }

                //单价
                float fee = Float.parseFloat(total_fee) / 100 / payIdCount;
                //总价
                float fee1 = Float.parseFloat(total_fee) / 100;
                //支付的总金额相当于付款时的金额
                String payAmount = String.format("%1.2f", fee1);
                //支付的总金额/订单条数=每笔订单支付的单价
                String payUnit = String.format("%1.2f", fee);

                String settlePrice;
                if (fee <= StringOutputConstant.TEST_AMOUNT) {
                    settlePrice = "0.00";
                } else {
                    settlePrice = String.format("%1.2f", fee / 7);
                }
                logger.info("out_trade_no(订单号)为：" + out_trade_no + ";total_fee(金额)为:" + total_fee + ";payAmount为:" + payAmount + ";settlePrice为：" + settlePrice);

                //2，不管是不是成功的记录都需要去入库，根据支付id和金额入库：service_plan_order_record_t
                Integer upReCount = comLogicService.updateOrderRecordT(out_trade_no, payUnit, payAmount, fee_type, settlePrice, transaction_id, StringOutputConstant.CODE_PAY_WEIXIN, result_code, "1");

                if (upReCount > 0) {
                    logger.info(out_trade_no + ":service_plan_order_record_t更新记录成功");
                    //丢去redis做后面该做当然事情
                    afterPayDeal.addPayIdToRedis(out_trade_no);
                    //成功返回给微信端
                    return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }
            }
            //去数据库做微信流水记录
            Integer count = comLogicService.findCountByOutTradeNo(out_trade_no, transaction_id);
            if (count < 1) {
                //入库微信流水记录
                Integer insertCount = comLogicService.insertWeiXinResults(transaction_id, out_trade_no, total_fee, fee_type, result_code, return_code);
            }
            //按照访问记录非success来处理
            return "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[FAIL]]></return_msg>" + "</xml> ";
        }
        //通信标识(return_code)不是SUCCESS
        return "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[" + return_msg + "]]></return_msg>" + "</xml> ";
    }

    /**
     * payPal的ipn支付回调
     *
     * @param resStr
     * @return
     * @throws Exception
     */
    @Override
    public void ipn(String resStr) {

        if (StringUtils.isBlank(resStr)) {
            logger.info("ipn请求为空");
            return;
        }
        //将ipn的字符串按照&分割，然后将有param但是没有value值的用00补全，然后将param和value以键值对的方式存到map里面去
        Map<String, String> m = comLogicService.StringToMap(resStr);
        //只有map不是null才有得往下进行的必要
        if (null == m || m.isEmpty()) {
            logger.info("ipn解析map有误");
            return;
        }
        String payId = m.get("invoice") + "";
        String mount = m.get("mc_gross") + "";
        String currency = m.get("mc_currency") + "";
        String business = m.get("business") + "";
        String paymentStatus = m.get("payment_status") + "";
        String txnId = m.get("txn_id") + "";
        logger.info("收款账号是：" + business + ";收款金额：" + mount + "付款状态是：" + paymentStatus + ";付款订单：" + payId + ";流水号：" + txnId);

        if (StringUtils.isBlank(mount) || StringUtils.isBlank(paymentStatus)) {
            logger.info("返回的ipn中mc_gross或者paymentStatus为空");
            return;
        }
        if (StringUtils.isBlank(payId) || StringUtils.isBlank(currency) || StringUtils.isBlank(txnId)) {
            logger.info("返回的ipn主要的数据有误");
            return;
        }
        //状态是已完成的订单直接去数据库做最重要的事情就是更改支付成功的记录
        if (StringOutputConstant.CODE_COMPLETED.equalsIgnoreCase(paymentStatus) && StringUtils.isNotBlank(mount) && Float.parseFloat(mount) > StringOutputConstant.STANDARD_AMOUNT) {
            //查询out_trade_no在数据库有几条记录。查询不到这条记录可以直接返回
            Integer payIdCount = comLogicService.findCountByNo(payId);
            if (payIdCount <= 0) {
                logger.info("invoice:" + payId + "：不是领科系统的支付单号");
                return;
            }
            //单价
            float fee = Float.parseFloat(mount) / payIdCount;
            //总价
            float fee1 = Float.parseFloat(mount);
            //支付的总金额相当于付款时的金额
            String payAmount = String.format("%1.2f", fee1);
            //支付的总金额/订单条数=每笔订单支付的单价
            String payUnit = String.format("%1.2f", fee);
            //计算settlePrice
            String settlePrice = setSettlePrice(fee, currency);
            //先用收款账号直接定位是属于哪一家收款：
            String payAccount;
            if (StringOutputConstant.CODE_PAYPAL_EMAIL_LINKS.equals(business) || StringOutputConstant.CODE_PAYPAL_EMAIL_GARY.equals(business)) {
                //领科自己收款
                payAccount = "1";
            } else {
                //客户自己收款
                payAccount = "2";
            }
            //2，不管是不是成功的记录都需要去入库，根据支付id和金额入库：service_plan_order_record_t
            Integer upReCount = comLogicService.updateOrderRecordT(payId, payUnit, payAmount, currency, settlePrice, txnId, StringOutputConstant.CODE_PAY_PAYPAL, "SUCCESS", payAccount);
            if (upReCount > 0) {
                logger.info(payId + ":service_plan_order_record_t更新记录成功");
                //丢去redis做后面该做当然事情
                afterPayDeal.addPayIdToRedis(payId);
            }

            try {
                //最后将成功的payPal回传的成功的交易记录入库保存下来:notification_payment_results_paypal_t
                Integer count = paymentAndResultMapper.findResultsCountByInvoice(payId, txnId);
                if (count <= 0) {
                    //入库payPal流水记录
                    comLogicService.insertPayPalIpnResultsT(m.get("mc_gross"), m.get("invoice"), m.get("payment_status"), m.get("mc_currency"), m.get("txn_id"), m.get("protection_eligibility"),
                            m.get("address_status"), m.get("payer_id"), m.get("address_street"), m.get("payment_date"), m.get("charset"), m.get("address_zip"), m.get("first_name"), m.get("mc_fee"),
                            m.get("address_country_code"), m.get("address_name"), m.get("notify_version"), m.get("custom"), m.get("payer_status"), m.get("business"), m.get("address_country"), m.get("address_city"),
                            m.get("quantity"), m.get("verify_sign"), m.get("payer_email"), m.get("payment_type"), m.get("last_name"), m.get("address_state"), m.get("receiver_email"), m.get("payment_fee"),
                            m.get("receiver_id"), m.get("txn_type"), m.get("item_name"), m.get("item_number"), m.get("residence_country"), m.get("receipt_id"), m.get("transaction_subject"),
                            m.get("payment_gross"), m.get("ipn_track_id"));
                    logger.info(txnId + "流水记录成功");
                }

            } catch (Exception e) {
                //如果入库发生异常，可能是字符编码不符合，就直接把ipn远字符串存起来
                Integer eInsertCount = comLogicService.insertExceptionIpnStr(mount, payId, paymentStatus, currency, txnId, business, m.get("payer_email"), resStr);
                if (eInsertCount > 0) {
                    logger.info(payId + "ipn成功支付记录异常入库成功");
                }
            }
        }

        try {
            //为了把payPal申诉退款的记录全部记下：
            if (!StringOutputConstant.CODE_COMPLETED.equalsIgnoreCase(paymentStatus)) {
                //入库payPal申诉退款记录
                comLogicService.insertPayPalReversedT(m.get("mc_gross"), m.get("invoice"), m.get("payment_status"), m.get("mc_currency"), m.get("txn_id"), m.get("parent_txn_id"), m.get("protection_eligibility"),
                        m.get("address_status"), m.get("payer_id"), m.get("address_street"), m.get("payment_date"), m.get("charset"), m.get("address_zip"), m.get("first_name"), m.get("mc_fee"),
                        m.get("address_country_code"), m.get("address_name"), m.get("notify_version"), m.get("custom"), m.get("payer_status"), m.get("business"), m.get("address_country"), m.get("address_city"),
                        m.get("quantity"), m.get("verify_sign"), m.get("payer_email"), m.get("payment_type"), m.get("last_name"), m.get("address_state"), m.get("receiver_email"), m.get("payment_fee"),
                        m.get("receiver_id"), m.get("txn_type"), m.get("item_name"), m.get("item_number"), m.get("residence_country"), m.get("receipt_id"), m.get("transaction_subject"),
                        m.get("payment_gross"), m.get("ipn_track_id"));
                logger.info(m.get("parent_txn_id") + ":当前流水号：" + m.get("txn_id") + "：申诉记录记录成功");
            }
        } catch (Exception e) {
            //如果入库发生异常，可能是字符编码不符合，就直接把ipn远字符串存起来
            logger.info(payId + "ipn申诉记录入库异常");

        }
    }

    /**
     * payPal的webHook支付回调
     *
     * @param resStr
     */
    @Override
    public String webHook(String resStr) {

        logger.info("payPal的webHook回调的内容是：" + resStr);
//
//        try {
//            if (StringUtils.isBlank(resStr)) {
//                logger.info("webHook请求为空");
//                return null;
//            }
//
//            if (null == JSON.parseObject(resStr, JsonRootBean.class)) {
//                logger.info("请求jsonRootBean参数为null");
//                return null;
//            }
//
//            JsonRootBean jsonRootBean = JSON.parseObject(resStr, JsonRootBean.class);
//            if (null == jsonRootBean.getResource()) {
//                logger.info("请求jsonRootBean参数为null");
//                return null;
//            }
//
//            com.payment.entity.payresults.paypal.Resource resource = jsonRootBean.getResource();
//
//            //内部有用的数据
//            if (StringUtils.isNotBlank(resource.getId()) && StringUtils.isNotBlank(resource.getInvoice_number()) && StringUtils.isNotBlank(resource.getState()) &&
//                    null != resource.getAmount() && null != resource.getTransaction_fee()) {
//
//                //Resource
//                String paypal_id = resource.getId() + "";
//                String payId = resource.getInvoice_number() + "";
//                String state = resource.getState() + "";
//                String parent_payment = resource.getParent_payment() + "";
//                String payment_mode = resource.getPayment_mode() + "";
//                String protection_eligibility = resource.getProtection_eligibility() + "";
//                String protection_eligibility_type = resource.getProtection_eligibility_type() + "";
//
//                //Transaction_fee
//                Transaction_fee transaction_fee = resource.getTransaction_fee();
//
//                //Amount
//                Amount amount = resource.getAmount();
//                if (StringUtils.isNotBlank(amount.getTotal()) && StringUtils.isNotBlank(amount.getCurrency()) && null != amount.getDetails()) {
//
//                    String mount = amount.getTotal();
//                    String currency = amount.getCurrency();
//                    Details details = amount.getDetails();
//
//                    if (StringUtils.isNotBlank(details.getSubtotal()) && StringUtils.isNotBlank(transaction_fee.getValue()) && StringUtils.isNotBlank(transaction_fee.getCurrency())) {
//
//                        String subtotal = details.getSubtotal();
//                        String value = transaction_fee.getValue();
//                        String currencys = transaction_fee.getCurrency();
//
//                        //入库payPal的webHook回调流水记录：
//                        Integer c = paymentAndResultMapper.findCountByInvoiceNumber(payId, paypal_id);
//                        if (c <= 0) {
//                            comLogicService.insertPayPalWebHookResults(paypal_id, state, payId, payment_mode, protection_eligibility, protection_eligibility_type, parent_payment, mount, currency, subtotal, value, currencys);
//                        }
//
//                        //状态是已完成的订单才用去数据库更新订单数据
//                        if (StringOutputConstant.CODE_COMPLETED.equalsIgnoreCase(state)) {
//
//                            //1，查询订单数据表中此条记录有没有入过库，入过库可以直接返回
//                            Integer orderCount = paymentAndResultMapper.findSuccessCountByRecord(payId);
//                            if (orderCount > 0) {
//                                logger.info(payId + "：记录已入库过");
//                                return "SUCCESS";
//                            }
//
//                            //2，查询out_trade_no在数据库有几条记录。查询不到这条记录可以直接返回
//                            Integer payIdCount = comLogicService.findCountByNo(payId);
//                            if (payIdCount <= 0) {
//                                logger.info("invoice:" + payId + "：不是领科系统的支付单号");
//                                return null;
//                            }
//
//                            //3,判断下去更新数据库的结果
//                            String code = comLogicService.orderDataProcessing("2", payId, mount, currency, paypal_id, StringOutputConstant.CODE_PAY_PAYPAL, "1", "SUCCESS", payIdCount);
//
//                            //5，这边开始判断是不是成功的返回，目的是只有成功的支付行为才需要去北京做真正的订购操作
//
//                            if (StringOutputConstant.CODE_SUCCESS.equals(code)) {
//
//                                //6,去订购套餐
//                                String results = comLogicService.purchasePlan(payId);
//
//                                if (StringUtils.isNotBlank(results)) {
//                                    logger.info("webHook【订购操作】:" + results);
//                                    return "SUCCESS";
//                                } else {
//                                    logger.info("webHook【订购操作】失败");
//                                    return "SUCCESS";
//                                }
//                            } else {
//                                logger.info("webHook数据更新数据库有误");
//                                return "SUCCESS";
//                            }
//
//                        } else {
//                            logger.info("返回的webHook数据状态是：" + state);
//                            return "SUCCESS";
//                        }
//
//                    } else {
//                        logger.info("payPal的webHook回调subtotal参数有误");
//                        return null;
//                    }
//                } else {
//                    logger.info("payPal的webHook回调amount参数有误");
//                    return null;
//                }
//            } else {
//                logger.info("payPal的webHook回调resource参数有误");
//                return null;
//            }
//        } catch (Exception e) {
//            logger.info("webHook回调数据处理发生异常" + e);
//            return null;
//        }
        return null;
    }

    /**
     * 获取展示微信支付的渠道集合
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto showWeChatPay(RequestShowWeChatPay request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }

        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }

        String sign = Md5Encrypt.jsonSign(request);

        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }
        List<PartnerShowWeChatPay> codeList = paymentAndResultMapper.queryShowWeChatPayCodeList();
        if (null == codeList || codeList.isEmpty()) {
            logger.info("查询到的渠道编码集合是空的");
            return ResultDataDto.addOperationFailure("");
        }
        //把数据库获取到的对象遍历
        List<String> list = new ArrayList<String>();
        for (PartnerShowWeChatPay code : codeList) {
            list.add(code.getPartnerCode());
        }

        String[] partnerCode = list.toArray(new String[list.size()]);
        ResponseShowWeChatPay response = new ResponseShowWeChatPay();
        response.setPartnerCode(partnerCode);

        return ResultDataDto.addOperationSuccess().setData(response);
    }

    /**
     * stripe一次性支付结果回调
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripeCallback(String request) {
        if (StringUtils.isBlank(request)) {
            logger.info("stripe支付回调为空");
            return ResultDataDto.addOperationFailure("stripe支付回调为空");
        }
        StripeJsonRootBean stripe;
        try {
            stripe = JSON.parseObject(request, StripeJsonRootBean.class);
        } catch (Exception e) {
            logger.info("Stripe支付回调解析异常：" + e);
            return ResultDataDto.addOperationFailure("stripe返回的数据有误");
        }
        List<ChargesData> data = stripe.getCharges().getData();
        String txnId = "";
        for (ChargesData chargesData : data) {
            /*charges的id*/
            txnId = chargesData.getId() + "";
        }
        String payId = stripe.getDescription() + "";
        String mount = stripe.getAmount() + "";
        //String currency = stripe.getCurrency() + "";
        String receiptEmail = stripe.getReceiptEmail() + "";
        String customer = stripe.getCustomer() + "";
        String status = stripe.getStatus() + "";
        /*大的对象的id*/
        String id = stripe.getId() + "";
        /*基本为null*/
        String invoice = stripe.getInvoice() + "";
        String pmId = stripe.getPaymentMethod() + "";
        logger.info("收款账号是：" + receiptEmail + ";收款金额：" + mount + "付款状态是：" + status + ";付款订单：" + payId + ";流水号：" + txnId);
        if (StringUtils.isBlank(payId) || StringUtils.isBlank(mount) || StringUtils.isBlank(stripe.getCurrency() + "") || StringUtils.isBlank(status) || StringUtils.isBlank(txnId)) {
            logger.info("stripe返回的主要数据有误");
            return ResultDataDto.addOperationFailure("stripe返回的主要数据有误");
        }
        String currency = "";
        if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.USD)) {
            currency = StringOutputConstant.USD;
        } else if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.EUR)) {
            currency = StringOutputConstant.EUR;
        } else if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.CNY)) {
            currency = StringOutputConstant.CNY;
        }
        //状态是成功的订单直接去数据库做最重要的事情就是更改支付成功的记录
        if (StringOutputConstant.CODE_SUCCEEDED.equalsIgnoreCase(status) && StringUtils.isNotBlank(mount) && Float.parseFloat(mount) > StringOutputConstant.STANDARD_AMOUNT) {
            //查询payId在数据库有几条记录。查询不到这条记录可以直接返回
            Integer payIdCount = comLogicService.findCountByNo(payId);
            if (payIdCount <= 0) {
                logger.info("description:" + payId + "：不是领科系统的支付单号");
                return ResultDataDto.addOperationFailure(payId + ":不是B2B2C的支付订单");
            }
            //单价
            float fee = Float.parseFloat(mount) / 100 / payIdCount;
            //总价
            float fee1 = Float.parseFloat(mount) / 100;
            //支付的总金额相当于付款时的金额
            String payAmount = String.format("%1.2f", fee1);
            //支付的总金额/订单条数=每笔订单支付的单价
            String payUnit = String.format("%1.2f", fee);
            //计算settlePrice
            String settlePrice = setSettlePrice(fee, currency);

            //2，不管是不是成功的记录都需要去入库，根据支付id和金额入库：service_plan_order_record_t
            Integer upReCount = comLogicService.updateOrderRecordT(payId, payUnit, payAmount, currency, settlePrice, txnId, StringOutputConstant.CODE_PAY_STRIPE, "SUCCESS", "1");
            if (upReCount > 0) {
                logger.info(payId + ":service_plan_order_record_t更新记录成功");
                //丢去redis做后面该做当然事情
                afterPayDeal.addPayIdToRedis(payId);
            }
            //最后将成功的Stripe回传的成功的交易记录入库保存下来：payment_transaction_stripe_t   把大的id当成invoice用
            //Integer count = paymentAndResultMapper.findStripeResultsById(payId, txnId, invoice);

            Integer count = paymentAndResultMapper.findStripeResultsById(payId, txnId, id);
            if (count <= 0) {
                //入库payPal流水记录   把大的id当成invoice用
                //Integer insertStripeCount = comLogicService.insertStripePayment(payId, payAmount, currency, receiptEmail, customer, txnId, invoice, status, pmId, request);

                Integer insertStripeCount = comLogicService.insertStripePayment(payId, payAmount, currency, receiptEmail, customer, txnId, id, status, pmId, request);
                if (insertStripeCount > 0) {
                    logger.info(txnId + ":Stripe流水记录成功");
                }
            }
        } else {
            //收款失败
            logger.info(status + "Stripe流水数据状态有误");
        }
        //返回
        return ResultDataDto.addOperationSuccess();
    }

    /**
     * stripe自动续费订阅支付结果回调
     * <p>
     * payId从HttpServletRequest的Header传过来的
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripeAutoSubCallback(HttpServletRequest re, String request) {
        if (StringUtils.isBlank(request)) {
            logger.info("stripe订阅回调为空");
            return ResultDataDto.addOperationFailure("stripe订阅回调为空");
        }
        if (StringUtils.isBlank(re.getHeader("payId"))) {
            logger.info("Header中payId为空");
            return ResultDataDto.addOperationFailure("stripe订阅回调Header为空");
        }
        StripeSubJsonBody stripe;
        try {
            stripe = JSON.parseObject(request, StripeSubJsonBody.class);
        } catch (Exception e) {
            logger.info("stripe订阅回调解析异常：" + e);
            return ResultDataDto.addOperationFailure("stripe订阅返回的数据有误");
        }
        String payId = re.getHeader("payId") + "";
        String invoice = stripe.getInvoice() + "";
        String mount = stripe.getAmount() + "";
        //总价
        float fee2 = Float.parseFloat(mount) / 100;
        //支付的总金额相当于付款时的金额
        String amount = String.format("%1.2f", fee2);
        //String currency = stripe.getCurrency() + "";
        //String receiptEmail = stripe.getReceiptEmail() + "";
        String customer = stripe.getCustomer() + "";
        String status = stripe.getStatus() + "";
        String txnId = stripe.getId() + "";
        //此值也许会根据不同的信用卡变动，所以不能当唯一值
        String pmId = stripe.getPaymentMethod() + "";
        logger.info("订单号payId：" + payId + ";收款账号是：" + receiptEmail + ";收款金额：" + mount + "付款状态是：" + status + ";订阅单号：" + pmId + ";流水号：" + txnId);
        if (StringUtils.isBlank(pmId) || StringUtils.isBlank(mount) || StringUtils.isBlank(stripe.getCurrency() + "") || StringUtils.isBlank(status) || StringUtils.isBlank(txnId) || StringUtils.isBlank(customer)) {
            logger.info("stripe订阅返回的主要数据有误");
            return ResultDataDto.addOperationFailure("stripe订阅返回的主要数据有误");
        }
        String currency = "";
        if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.USD)) {
            currency = StringOutputConstant.USD;
        } else if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.EUR)) {
            currency = StringOutputConstant.EUR;
        } else if (stripe.getCurrency().equalsIgnoreCase(StringOutputConstant.CNY)) {
            currency = StringOutputConstant.CNY;
        }
        //状态是成功的订单直接去数据库做最重要的事情就是更改支付成功的记录
        if (StringOutputConstant.CODE_SUCCEEDED.equalsIgnoreCase(status) && StringUtils.isNotBlank(mount) && Float.parseFloat(mount) > StringOutputConstant.STANDARD_AMOUNT) {
            ServicePlanOrderAutoRenewalRecord autoRecord = paymentAndResultMapper.queryAutoRecord(payId);
            if (null != autoRecord) {
                //这边要判断一下重复的回调情况：
                Integer cou = paymentAndResultMapper.queryRecordById(txnId, status, payId, autoRecord.getPlanId(), pmId);
                if (cou > 0) {
                    logger.info(pmId + ":重复的回调");
                    return ResultDataDto.addOperationFailure("stripe:重复的回调");
                }
                //说明订阅回调不是第一次回来:1,先在写多一行数据
                ServicePlanOrderAutoRenewalRecord record = new ServicePlanOrderAutoRenewalRecord();
                record.setTxnId(txnId);
                record.setInvoice(invoice);
                record.setPayRst(status);
                record.setPartnerCode(autoRecord.getPartnerCode());
                record.setDeviceCode(autoRecord.getDeviceCode());
                record.setPayId(payId);
                record.setAmount(amount);
                record.setCurrency(currency);
                record.setIntervals(autoRecord.getIntervals());
                record.setIntervalCount(autoRecord.getIntervalCount());
                record.setNickName(autoRecord.getNickName());
                record.setPlanId(autoRecord.getPlanId());
                record.setPmId(pmId);
                record.setSubId(autoRecord.getSubId());
                record.setProductId(autoRecord.getProductId());
                record.setPayMethod(autoRecord.getPayMethod());
                record.setCustomerId(autoRecord.getCustomerId());
                record.setStatus(autoRecord.getStatus());
                record.setEmail(autoRecord.getEmail());
                record.setReceiptEmail(receiptEmail);
                Integer count = paymentAndResultMapper.insertAutoRenewalRecord(record);
                if (count > 0) {
                    logger.info("【Stripe自动订阅回调】入库成功");
                }
                //根据partnerCode和payId去查询订单记录表里面有没有这条记录
                List<ServicePlanOrderRecord> recordList = paymentAndResultMapper.queryRecordExists(autoRecord.getPartnerCode(), payId);
                if (null == recordList || recordList.isEmpty()) {
                    logger.info("数据库不存在此条支付订单记录");
                    return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PAYID_ILLEGAL_ERROR);
                }
                //更新了一条之后要去订单记录表中添加一条记录了
                Integer insertReCount = comLogicService.insertRecord(recordList, txnId, invoice);
                if (insertReCount > 0) {
                    logger.info("补写一条订单记录成功");
                    //丢去redis做后面该做当然事情
                    afterPayDeal.addPayIdToRedis(payId);
                }
            } else {
                //说明回调的结果第一次回来：1，先去数据库更新记录
                Integer count = paymentAndResultMapper.updateAutoRenewalRecord(txnId, invoice, status, payId);
                if (count > 0) {
                    logger.info("【Stripe自动订阅回调】更新成功");
                }
                //查询payId在数据库有几条记录。查询不到这条记录可以直接返回
                Integer payIdCount = comLogicService.findCountByNo(payId);
                if (payIdCount <= 0) {
                    logger.info("payId:" + payId + "：不是领科系统的支付单号");
                    return ResultDataDto.addOperationFailure(payId + ":不是B2B2C的支付订单");
                }
                //单价
                float fee = Float.parseFloat(mount) / 100 / payIdCount;
                //总价
                float fee1 = Float.parseFloat(mount) / 100;
                //支付的总金额相当于付款时的金额
                String payAmount = String.format("%1.2f", fee1);
                //支付的总金额/订单条数=每笔订单支付的单价
                String payUnit = String.format("%1.2f", fee);
                //计算settlePrice
                String settlePrice = setSettlePrice(fee, currency);

                //2，不管是不是成功的记录都需要去入库，根据支付id和金额入库：service_plan_order_record_t
                Integer upReCount = comLogicService.updateOrderRecordT(payId, payUnit, payAmount, currency, settlePrice, txnId, StringOutputConstant.CODE_PAY_STRIPE, "SUCCESS", "1");
                if (upReCount > 0) {
                    logger.info(payId + ":service_plan_order_record_t更新记录成功");
                    //丢去redis做后面该做当然事情
                    afterPayDeal.addPayIdToRedis(payId);
                }
            }
            //最后将成功的Stripe回传的成功的交易记录入库保存下来：payment_transaction_stripe_t
            Integer count = paymentAndResultMapper.findStripeResultsById(payId, txnId, invoice);
            if (count <= 0) {
                //入库payPal流水记录
                Integer insertStripeCount = comLogicService.insertStripePayment(payId, amount, currency, receiptEmail, customer, txnId, invoice, status, pmId, request);
                if (insertStripeCount > 0) {
                    logger.info(txnId + ":Stripe流水记录成功");
                }
            }
        } else {
            //收款失败
            logger.info(status + "Stripe流水数据状态有误");
        }
        //返回
        return ResultDataDto.addOperationSuccess();
    }

    /**
     * 请求：获取Stripe收银台一次性支付权限
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripePay(RequestStripePay request) {

        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("获取Stripe一次性支付权限请求：" + JSON.toJSONString(request));
        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getPartnerCode()) ||
                StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount()) || StringUtils.isBlank(request.getPayCurrency()) ||
                StringUtils.isBlank(request.getEmail()) || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }
        String sign = Md5Encrypt.jsonSign(request);
        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }
        //参数没有问题的时候就去北京请求收银台
        CreateStripePaymentResponse response = toBeijingCheckoutService.createStripePayment(request);
        if (null == response || null == response.getData() || StringUtils.isBlank(response.getData().getPublishableKey()) || StringUtils.isBlank(response.getData().getClientSecret())) {
            return ResultDataDto.addOperationFailure();
        }
        logger.info("【Stripe一次性支付】成功响应" + JSON.toJSONString(response.getData()));
        return ResultDataDto.addOperationSuccess().setData(response.getData());
    }

    /**
     * 获取stripe收银台自动续费支付权限
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripeAutoPay(RequestStripeAutoPay request) {
        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("获取Stripe自动续费支付权限请求：" + JSON.toJSONString(request));
        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getPartnerCode()) ||
                StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount()) || StringUtils.isBlank(request.getPayCurrency()) ||
                StringUtils.isBlank(request.getEmail()) || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }
        String sign = Md5Encrypt.jsonSign(request);
        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }
        List<ServicePlanOrderRecord> recordList = paymentAndResultMapper.queryRecordExists(request.getPartnerCode(), request.getPayId());
        if (null == recordList || recordList.isEmpty()) {
            logger.info("数据库不存在此条支付订单记录");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PAYID_ILLEGAL_ERROR);
        }

        String email = "";
        for (ServicePlanOrderRecord record : recordList) {
            String deviceCode = record.getDeviceCode();
            email = deviceCode + "@qq.com";
        }
        //参数没有问题的时候就去北京请求收银台
        SetupIntentResponse response = toBeijingCheckoutService.setupIntent(request, email);
        if (null == response || null == response.getData() || StringUtils.isBlank(response.getData().getPublishableKey()) || StringUtils.isBlank(response.getData().getClientSecret()) || StringUtils.isBlank(response.getData().getCustomer_id())) {
            return ResultDataDto.addOperationFailure();
        }
        logger.info("【Stripe自动续费】成功响应" + JSON.toJSONString(response.getData()));
        return ResultDataDto.addOperationSuccess().setData(response.getData());
    }

    /**
     * 获取stripe收银台自动续费直接订阅
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripeSubDirectly(RequestStripeSubDirectly request) {
        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("获取Stripe自动续费直接订阅请求：" + JSON.toJSONString(request));
        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getPartnerCode()) ||
                StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getPayAmount()) || StringUtils.isBlank(request.getPayCurrency()) || StringUtils.isBlank(request.getEmail()) ||
                StringUtils.isBlank(request.getPlan_id()) || StringUtils.isBlank(request.getPm_id()) || StringUtils.isBlank(request.getSign())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }
        String sign = Md5Encrypt.jsonSign(request);
        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }
        List<ServicePlanOrderRecord> recordList = paymentAndResultMapper.queryRecordExists(request.getPartnerCode(), request.getPayId());
        if (null == recordList || recordList.isEmpty()) {
            logger.info("数据库不存在此条支付订单记录");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PAYID_ILLEGAL_ERROR);
        }
        String amount = "";
        String currency = "";
        String interval = "";
        String intervalCount = "";
        String nickName = "";
        String planId = "";
        String packageName = "";
        String packageCode = "";
        String deviceCode = "";
        String email = "";
        SubscriptionDirectlyPlan plan = null;
        SubscriptionDirectlyProduct product = null;
        for (ServicePlanOrderRecord record : recordList) {
            amount = record.getPayAmount();
            currency = record.getPayCurrency();
            interval = "";
            intervalCount = "";
            nickName = record.getOrderPeriod() + "*" + record.getPackageName();
            planId = request.getPlan_id();
            packageName = record.getPackageName();
            packageCode = record.getPackageCode();
            deviceCode = record.getDeviceCode();
            email = deviceCode + "@qq.com";

            plan = new SubscriptionDirectlyPlan();
            plan.setAmount(amount);
            plan.setCurrency(currency);
            if (Constant.CODE_ZERO.equals(record.getPackageType()) || Constant.CODE_ONE.equals(record.getPackageType())) {
                interval = "Day";
                intervalCount = record.getOrderPeriod();
            } else if (Constant.CODE_TWO.equals(record.getPackageType())) {
                interval = "Month";
                intervalCount = record.getOrderPeriod();
            } else if (Constant.CODE_THREE.equals(record.getPackageType())) {
                interval = "Month";
                intervalCount = String.valueOf(Integer.parseInt(record.getOrderPeriod()) * 3);
            } else if (Constant.CODE_FOUR.equals(record.getPackageType())) {
                interval = "Month";
                intervalCount = String.valueOf(Integer.parseInt(record.getOrderPeriod()) * 6);
            } else if (Constant.CODE_FIVE.equals(record.getPackageType())) {
                interval = "Year";
                intervalCount = record.getOrderPeriod();
            }
            plan.setInterval(interval);
            plan.setInterval_count(intervalCount);
            plan.setNick_name(nickName);
            plan.setPlan_id(planId);

            product = new SubscriptionDirectlyProduct();
            product.setDescription(packageName);
            product.setPackage_code(packageCode);
        }
        SubscriptionDirectlyRequest re = new SubscriptionDirectlyRequest();
        re.setEmail(email);
        re.setOrder_id(request.getPayId());
        re.setPartnerCode(request.getPartnerCode());
        re.setPm_id(request.getPm_id());
        re.setReceipt_email(receiptEmail);
        re.setPlan(plan);
        re.setProduct(product);

        //参数没有问题的时候就去北京请求收银台
        SubscriptionDirectlyResponse response = toBeijingCheckoutService.directly(re);
        if (null == response || null == response.getData()) {
            return ResultDataDto.addOperationFailure();
        }
        //入库
        ServicePlanOrderAutoRenewalRecord autoRecord = new ServicePlanOrderAutoRenewalRecord();
        autoRecord.setPartnerCode(request.getPartnerCode());
        autoRecord.setDeviceCode(deviceCode);
        autoRecord.setPayId(request.getPayId());
        autoRecord.setAmount(amount);
        autoRecord.setCurrency(currency);
        autoRecord.setIntervals(interval);
        autoRecord.setIntervalCount(intervalCount);
        autoRecord.setNickName(nickName);
        autoRecord.setPlanId(planId);
        autoRecord.setPmId(request.getPm_id());
        autoRecord.setSubId(response.getData().getSub_id());
        autoRecord.setProductId(response.getData().getProduct_id());
        autoRecord.setPayMethod(response.getData().getPay_method());
        autoRecord.setCustomerId(response.getData().getCustomer_id());
        autoRecord.setStatus(response.getData().getStatus());
        autoRecord.setEmail(email);
        autoRecord.setReceiptEmail(receiptEmail);

        Integer count = paymentAndResultMapper.insertAutoRenewalRecord(autoRecord);
        if (count > 0) {
            logger.info("【Stripe自动续费】入库成功");
        }

        logger.info("【Stripe自动续费】成功响应" + JSON.toJSONString(response.getData()));
        return ResultDataDto.addOperationSuccess().setData(response.getData());
    }

    /**
     * 获取stripe收银台自动续费取消订阅
     *
     * @param request
     * @return
     */
    @Override
    public ResultDataDto stripeSubCancel(RequestStripeSubCancel request) {
        if (null == request || StringUtils.isBlank(JSON.toJSONString(request))) {
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_REQUEST_EMPTY);
        }
        logger.info("获取Stripe自动续费取消订阅请求：" + JSON.toJSONString(request));
        if (StringUtils.isBlank(request.getTradeType()) || StringUtils.isBlank(request.getTradeTime()) || StringUtils.isBlank(request.getVersion()) || StringUtils.isBlank(request.getSign()) ||
                StringUtils.isBlank(request.getPartnerCode()) || StringUtils.isBlank(request.getPayId()) || StringUtils.isBlank(request.getEmail()) ||
                StringUtils.isBlank(request.getPlan_id()) || StringUtils.isBlank(request.getPm_id()) || StringUtils.isBlank(request.getSub_id())) {
            logger.info("请求参数不合法");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_PARAM_ERROR);
        }
        String sign = Md5Encrypt.jsonSign(request);
        if (!request.getSign().equalsIgnoreCase(sign)) {
            logger.info("签名验证失败");
            return ResultDataDto.addOperationFailure(StringOutputConstant.CODE_SIGN_ERROR);
        }
        //参数没有问题的时候就去北京请求收银台
        SubscriptionCancelResponse response = toBeijingCheckoutService.cancel(request);
        if (null == response || null == response.getData()) {
            return ResultDataDto.addOperationFailure();
        }
        ServicePlanOrderAutoRenewalRecord autoRecord = new ServicePlanOrderAutoRenewalRecord();
        autoRecord.setPeriodEnd(response.getData().getPeriod_end());
        autoRecord.setCurrentPeriodStart(response.getData().getCurrent_period_start());
        autoRecord.setCustomerId(response.getData().getCustomer());
        autoRecord.setStatus(response.getData().getStatus());
        autoRecord.setPmId(request.getPm_id());
        autoRecord.setPlanId(request.getPlan_id());
        autoRecord.setPayId(request.getPayId());
        Integer count = paymentAndResultMapper.updateCancelAutoRenewalRecord(autoRecord);
        if (count > 0) {
            logger.info("【Stripe自动续费】取消成功");
        }
        logger.info("【Stripe自动续费取消订阅】成功响应" + JSON.toJSONString(response.getData()));
        return ResultDataDto.addOperationSuccess().setData(response.getData());
    }
}

